﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TileMaker
{
    struct TileCoordinates
    {
        private byte _lvl;
        public byte Level { get { return _lvl; } set { _lvl = value; } }

        private int _lat;
        public int Latitude { get { return _lat; } set { _lat = value; } }

        public double LatitudeCoords { get { return getcoords(_lat, _lvl); } }
        public double LongitudeCoords { get { return getcoords(_lat, _lvl); } }

        private int _lon;
        public int Longitude { get { return _lon; } set { _lon = value; } }

        public TileCoordinates(byte Level, int Latitude, int Longitude)
        {
            _lvl = Level;
            _lat = Latitude;
            _lon = Longitude;
        }

        public TileCoordinates(byte Level, double LatCoords, double LonCoords)
        {
            TileCoordinates tmp = GetTile(Level, LatCoords, LonCoords);

            _lvl = Level;
            _lat = tmp.Latitude;
            _lon = tmp.Longitude;
        }

        public static TileCoordinates GetTile(byte Level, double LatCoord, double LonCoord)
        {
            int TileLat = (int)Math.Round(GetTilesCount(Level)[0] * (LatCoord / 90.0));
            int TileLon = (int)Math.Round(GetTilesCount(Level)[1] * (LonCoord / 180.0));

            return new TileCoordinates(Level, TileLat, TileLon);
        }

        public static int[] GetTilesCount(byte level)
        {
            return new int[] { (int)Math.Round(Math.Pow(2, 7 + level)), (int)Math.Round(Math.Pow(2, 8 + level)) };
        }

        public int[] GetTilesCount()
        {
            return GetTilesCount(_lvl);
        }

        /// <summary>
        /// Latitude then Longitude.
        /// </summary>
        /// <param name="tile"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        private double getcoords(double tile, byte level)
        {
            double num = 45 * tile;
            double den = GetTilesCount(level)[1]/4.0;

            return num / den;
        }
    }
}
